package com.tdam2011.grupo05.ui.activities.message;

import android.app.Activity;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.database.content.TdamContentProvider;
import com.tdam2011.grupo05.entities.contact.ContactWeb;

public class SelectContactFragment extends ListFragment {

	private static final String TAG = "SelectContactFragment";

	interface UsuarioCallback {
		void onSelectedUser(long idContact);

	}

	private UsuarioCallback listener;
	private SimpleCursorAdapter mAdapter;

	private final LoaderCallbacks<Cursor> mContactLoader = new LoaderCallbacks<Cursor>() {

		@Override
		public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
			Log.d(TAG, "onCreateLoader");
			return new CursorLoader(getActivity(),
					TdamContentProvider.USER_CONTENT_URI, new String[] {
							ContactWeb.COL_ID, ContactWeb.COL_ID_PHONE,
							ContactWeb.COL_ID_CONTACTO, ContactWeb.COL_NAME },
					null, null, null);
		}

		@Override
		public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
			Log.d(TAG, "on load finished: cursor=" + cursor.getCount());
			if (cursor != null) {
				mAdapter.swapCursor(cursor);
			}
		}

		@Override
		public void onLoaderReset(Loader<Cursor> arg0) {
			mAdapter.swapCursor(null);
		}

	};

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		listener = (UsuarioCallback) activity;

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_select_contact,
				container, false);

		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		setRetainInstance(true);

		mAdapter = new SimpleCursorAdapter(getActivity(),
				android.R.layout.simple_list_item_1, null,
				new String[] { ContactWeb.COL_NAME },
				new int[] { android.R.id.text1 }, 0);
		setListAdapter(mAdapter);
		getLoaderManager().initLoader(0, null, mContactLoader);

	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		if (listener != null) {
			CursorWrapper cw = (CursorWrapper) mAdapter.getItem(position);
			listener.onSelectedUser(cw.getLong(cw
					.getColumnIndex(ContactWeb.COL_ID)));
		}

	}
}
